﻿using CommunicationClass.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CommunicationClass.Auxiliary
{
    /// <summary>
    /// 接收消息数据转换
    /// </summary>
   public static class ReceiveLengthCalculation
    {
        /// <summary>
        /// 将接收到的数据转换成对应数据集合
        /// </summary>
        /// <typeparam name="ReceiveType">数据集合里面的类型</typeparam>
        /// <param name="data">接收到的byte集合</param>
        /// <returns>泛型数据集合</returns>
        public static List<ReceiveType> ReceiveMessageCalculation<ReceiveType>(byte[] datas,int length)
        {
            //返回的数据集合
            List<ReceiveType> ListSendModel = new List<ReceiveType>();
            try
            {
                byte[] data = datas.Take(length).ToArray();
                //读取出来消息内容
                while (true)
                {
                    //消息长度
                    int messagelength = 0;
                    //转换成string
                    string strlength = Encoding.Unicode.GetString(data.Skip(0).Take(MessageSendConfigure.MaxMessageSendLength * 2).ToArray());
                    //去除数据长度

                    data = data.Skip(MessageSendConfigure.MaxMessageSendLength * 2).Take(data.Length-(MessageSendConfigure.MaxMessageSendLength * 2)).ToArray();

                    if (int.TryParse(strlength, out messagelength))
                    {
                        
                        //判断数据是否完整
                        if (data.Length >= messagelength)
                        {
                            //数据完整

                            //截取数据,并且解压数据
                            byte[] json =data.Skip(0).Take(messagelength).ToArray();
                            data = data.Take(messagelength).Skip(data.Length - messagelength).ToArray();
                            ReceiveType sendModel = Auxiliary.JsonHelper.JsonDateDeserialize<ReceiveType>(json);
                            ListSendModel.Add(sendModel);
                            //截取掉上一条转换的数据

                            data = data.Take(0).Skip(data.Length - messagelength).ToArray();

                            //判断是否还存在数据
                            if (data.Length < 1)
                            {
                                break;
                            }
                        }
                        else
                        {
                            //数据不完整  垃圾数据  暂时不考虑 不存在
                            break;
                        }


                    }
                    else
                    {
                        //网络延迟间断数据,垃圾数据,暂时不考虑 不存在
                        break;
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
           
            return ListSendModel;
        }
    }
}
